import config from "../config/config.js"
const getCode = async function() {
	return new Promise((resolve, reject) => {
		uni.login({
			success: code => {
				console.log('获取code', code)
				resolve(code.code)
			}
		})
	})
}
const login = async function() {
	const code = await getCode();
	return new Promise((resolve, reject) => {
		// uni.showNavigationBarLoading()

		uni.showLoading({
					title: '加载中...',
					icon:'none'
				})
		uni.request({
			url: `${config.baseUrl}/wx/yulaw/user/${config.appid}/login?code=${code}`,
			method: 'get',
			success: res => {
				console.log(res.data, 'token')
				uni.setStorageSync('AUTH_TOKEN', res.data.data);
				uni.getUserInfo({
					success: (res3) => {
						console.log(res3, '授权成功', uni.getStorageSync('AUTH_TOKEN'));
						uni.request({
							url: `${config.baseUrl}/wx/yulaw/user/wxf60bdde4472ae369/info`,
							method: 'get',
							header: {
								token: uni.getStorageSync('AUTH_TOKEN')
							},
							data: {
								encryptedData: res3.encryptedData,
								iv: res3.iv,
							},
							success: res4 => {
								console.log('返回', res4.data.data);
								uni.setStorageSync('USER',JSON.stringify(res4.data.data))
								// uni.showModal({
								// 	content:res4.data.data,
								// 	title:res4.data.data
								// })
								uni.showToast({
									title: res4.data.data.nickName
								})
							}
						})
					},
					fail: () => {
						console.log("未授权");
					}
				})
				uni.redirectTo({
					url: '/pages/index/index'
				})
				resolve(res);
				uni.hideLoading()
			}

		})
	})
}
const checkToken = function() {
	const AUTH_TOKEN = uni.getStorageSync('AUTH_TOKEN');
	if (AUTH_TOKEN) {
		return true
	}
	return false
}
module.exports = {
	getCode,
	login,
	checkToken
}
